<template>
  <div>
    <div class="tabs">
      <a-tabs v-model:active-key="currentPortrait" :style="{ width: width - 130 + 'px' }" @change="getDurationListData()">
        <a-tab-pane v-for="item in portraitList" :key="item.portraitId" :title="item.portraitName"> </a-tab-pane>
      </a-tabs>
      <a-dropdown style="width: 160px">
        <a-button type="text">
          <template #icon>
            <icon-copy />
          </template>
          复制其他业务类型
        </a-button>
        <template #content>
          <a-doption v-for="item in portraitList">
            {{ item.portraitName }}
            <icon-copy @click="copy(item.portraitId)" />
          </a-doption>
        </template>
      </a-dropdown>
    </div>
    <a-scrollbar style="overflow-y: scroll; max-height: calc(100vh - 200px)">
      <div class="app-container">
        <div class="config">
          <div>是否需要开工确认<span>（例：通常情况下，软装业务不需要开工确认，此处可以选择“否”）</span></div>
          <a-radio-group v-model="durationConfig.startWork">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </div>
        <div class="tip">
          <span class="tip__title">工期配置</span>
          <span class="tip__desc"
            >（注：工期天数为开工日期，往后推算的自然天数，比如2024年1月1日开工，90天后就是2024年4月1日）</span
          >
        </div>
        <div class="table four-column-table">
          <div class="table-head">
            <div>面积<span>(m²)</span></div>
            <div>合同工期天数<span>(标准天数)</span></div>
            <div>内控工期</div>
            <div>操作</div>
          </div>
          <div class="table-body">
            <template v-for="(item, index) in durationConfig.durationDetailList">
              <a-form :model="item" :rules="durationDetailRules" ref="durationDetailRef">
                <div class="row">
                  <div v-if="item.durationSign == 1">
                    <a-form-item hide-label field="durationVal">
                      <div class="number-range">
                        <input type="number" disabled :value="previewMin(index)" />
                        <span>-</span>
                        <input
                          type="number"
                          placeholder="请输入"
                          v-model="item.durationVal"
                          @change="changeNumberRange(index)"
                          @blur="verifyItem(index)"
                        />
                      </div>
                    </a-form-item>
                  </div>
                  <div v-else>
                    <span class="outweigh">></span>
                    <a-form-item hide-label field="durationVal">
                      <a-input-number placeholder="请输入" v-model="item.durationVal" />
                    </a-form-item>
                  </div>
                  <div>
                    <a-form-item hide-label field="contractDuration">
                      <a-input-number placeholder="请输入" v-model="item.contractDuration" />
                    </a-form-item>
                  </div>
                  <div>{{ item.internalDuration }}天</div>
                  <div>
                    <a-button
                      v-if="index !== 0 && index !== durationConfig.durationDetailList.length - 1"
                      type="text"
                      size="mini"
                      @click="delDurationDetail(index)"
                      >删除</a-button
                    >
                    <span v-else>--</span>
                  </div>
                </div>
              </a-form>
            </template>
          </div>
          <div class="table-foot">
            <a-button type="text" size="mini" @click="addDuration">
              <template #icon>
                <icon-plus-circle-fill />
              </template>
              添加工期配置
            </a-button>
          </div>
        </div>
        <div class="tip">
          <span class="tip__title">其他场景</span>
        </div>
        <div class="table five-column-table" :style="{ '--column': 5 }">
          <div class="table-head">
            <div>场景名称</div>
            <div>类型</div>
            <div>合同工期天数<span>(标准天数基础上增减)</span></div>
            <div>内控工期</div>
            <div>操作</div>
          </div>
          <div class="table-body">
            <a-form
              v-for="(item, index) in durationConfig.durationOtherList"
              :model="item"
              ref="durationOtherRef"
              :rules="durationOtherRules"
            >
              <div class="row">
                <div>
                  <a-form-item hide-label field="otherName">
                    <a-input placeholder="请输入" v-model="item.otherName" />
                  </a-form-item>
                </div>
                <div>
                  <a-form-item hide-label field="otherType">
                    <a-select placeholder="请选择" v-model="item.otherType">
                      <a-option :value="1">增加工期</a-option>
                      <a-option :value="2">减少工期</a-option>
                    </a-select>
                  </a-form-item>
                </div>
                <div>
                  <a-form-item hide-label field="otherDates">
                    <a-input placeholder="请输入" v-model="item.otherDates" />
                  </a-form-item>
                </div>
                <div>根据标准天数计算</div>
                <div>
                  <a-button type="text" size="mini" @click="delDurationOtherLis(index)">删除</a-button>
                </div>
              </div>
            </a-form>
          </div>
          <div class="table-foot">
            <a-button type="text" size="mini" @click="addOtherScene">
              <template #icon>
                <icon-plus-circle-fill />
              </template>
              添加其他场景
            </a-button>
          </div>
        </div>
      </div>
    </a-scrollbar>
    <div class="save">
      <a-button type="primary" @click="save">保存</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { getPortraitList, getDurationList, updateDuration, getInternalDuration } from "@/apis/engineeringSettings/duration";
import type { PortraitItem, Duration, durationDetailListItem } from "@/apis/engineeringSettings/duration/type";
import { Message } from "@arco-design/web-vue";

defineProps(["width"]);
const portraitList = ref<PortraitItem[]>([]);
const durationConfig = ref<Duration>({
  durationId: "",
  portraitId: "",
  intervalDays: 0,
  startWork: 1,
  durationDetailList: [],
  durationOtherList: []
});
const currentPortrait = ref("");
const durationOtherRef = ref();
const durationDetailRef = ref();

const durationDetailRules = {
  durationVal: [
    { required: true, message: "请输入房屋面积区间" },
    { match: /^(?!0$)\d{1,12}$/, message: "请输入1到12位的正整数且大于0" }
  ],
  contractDuration: [
    { required: true, message: "请输入合同工期天数" },
    { match: /^(?!0$)\d{1,12}$/, message: "请输入1到12位的正整数且大于0" }
  ]
};
const durationOtherRules = {
  otherName: [
    { required: true, message: "请输入场景名称" },
    { maxLength: 30, message: "场景名称不能超过30个字符" }
  ],
  otherDates: [
    { required: true, message: "请输入合同工期天数" },
    { match: /^(?!0$)\d{1,12}$/, message: "请输入1到12位的正整数且大于0" }
  ],
  otherType: [{ required: true, message: "请选择类型" }]
};
/**
 * 用户画像
 */
const getPortraitListData = async () => {
  try {
    const res = await getPortraitList();
    portraitList.value = res.data || [];
    currentPortrait.value = res.data.length ? res.data[0].portraitId : "";
    getDurationListData();
  } catch (error) {}
};
/**
 * 获取工期列表
 */
const getDurationListData = async () => {
  try {
    await getDurationDay();
    const res = await getDurationList(currentPortrait.value);
    let durationDetailList;
    if (!res.data.durationDetailList.length) {
      const defaultDuration: durationDetailListItem = {
        durationSign: 2,
        durationVal: undefined,
        contractDuration: undefined,
        internalDuration: internalDuration.value
      } as durationDetailListItem;
      durationDetailList = [defaultDuration];
    } else {
      durationDetailList = res.data.durationDetailList.map(v => ({
        ...v,
        internalDuration: internalDuration.value,
        durationVal: Number(v.durationVal)
      }));
    }
    durationConfig.value = {
      ...res.data,
      durationDetailList
    };
  } catch (error) {}
};
const verify = async () => {
  let arr: Promise<boolean>[] = [];
  durationOtherRef.value?.forEach((item: any) => {
    arr.push(
      new Promise(resolve => {
        item.validate((error: any) => {
          resolve(error == undefined);
        });
      })
    );
  });
  durationDetailRef.value?.forEach((item: any) => {
    arr.push(
      new Promise(resolve => {
        item.validate((error: any) => {
          resolve(error == undefined);
        });
      })
    );
  });
  const result = await Promise.all(arr);
  return result.every(v => v);
};
const save = async () => {
  if (!(await verify())) return;
  try {
    await updateDuration(durationConfig.value);
    Message.success("保存成功");
    getDurationListData();
  } catch (error) {}
};
/**
 * 根据索引设置最小值
 */
const previewMin = (index: number) => {
  return index == 0 ? 0 : durationConfig.value.durationDetailList[index - 1].durationVal;
};
/**
 * 如果输入值小于最小值，则清空输入值
 */
const maxChange = (index: number) => {
  if (durationConfig.value.durationDetailList[index].durationVal == undefined) return;
  if (!index) {
    durationConfig.value.durationDetailList[index].durationVal =
      durationConfig.value.durationDetailList[index].durationVal < 0
        ? undefined
        : durationConfig.value.durationDetailList[index].durationVal;
  } else {
    if (durationConfig.value.durationDetailList[index - 1].durationVal == undefined) return;
    durationConfig.value.durationDetailList[index].durationVal =
      durationConfig.value.durationDetailList[index].durationVal <
      (durationConfig.value.durationDetailList[index - 1].durationVal as number)
        ? undefined
        : durationConfig.value.durationDetailList[index].durationVal;
  }
};
const addDuration = () => {
  const newItem = {
    durationVal: undefined,
    contractDuration: undefined,
    internalDuration: internalDuration.value,
    durationSign: 1
  };
  const index = durationConfig.value.durationDetailList.length - 1;
  durationConfig.value.durationDetailList?.splice(index, 0, newItem);
};
const verifyItem = (index: number) => {
  durationDetailRef.value[index].validateField(["durationVal"]);
};
/**
 * 当最大值大于后续最大值时，清空后续大于当前最大值的最大值
 */
const changeNumberRange = (index: number) => {
  maxChange(index);
  if (durationConfig.value.durationDetailList.length >= 2) {
    const currentVal = durationConfig.value.durationDetailList[index].durationVal;
    if (!currentVal) return;
    for (let i = index + 1; i <= durationConfig.value.durationDetailList.length; i++) {
      const nextVal = durationConfig.value.durationDetailList[i]?.durationVal;
      if (!nextVal) break;
      if (
        durationConfig.value.durationDetailList[i].durationVal &&
        (durationConfig.value.durationDetailList[i].durationVal as number) <= currentVal
      ) {
        durationConfig.value.durationDetailList[i].durationVal = undefined;
      }
    }
  }
};
/**
 * 添加其他场景
 */
const addOtherScene = () => {
  const newItem = {
    otherName: "",
    otherType: undefined,
    otherDates: undefined
  };
  durationConfig.value.durationOtherList.push(newItem);
};
const delDurationDetail = (index: number) => {
  durationConfig.value.durationDetailList.splice(index, 1);
};
const delDurationOtherLis = (index: number) => {
  durationConfig.value.durationOtherList.splice(index, 1);
};
const internalDuration = ref(0);
/**
 * 查询内部工期天数
 */
const getDurationDay = async () => {
  try {
    const res = await getInternalDuration(currentPortrait.value);
    internalDuration.value = res.data;
  } catch (error) {}
};
const copy = async (portraitId: string) => {
  try {
    await getDurationDay();
    const res = await getDurationList(portraitId);
    let durationDetailList;
    if (!res.data.durationDetailList.length) {
      const defaultDuration: durationDetailListItem = {
        durationSign: 2,
        durationVal: undefined,
        contractDuration: undefined,
        internalDuration: internalDuration.value
      } as durationDetailListItem;
      durationDetailList = [defaultDuration];
    } else {
      durationDetailList = res.data.durationDetailList;
    }
    const { startWork, durationOtherList } = res.data;
    durationConfig.value.startWork = startWork;
    durationConfig.value.durationOtherList = durationOtherList.map(v => ({
      ...v,
      durationId: undefined,
      durationOtherId: undefined,
      internalDuration: internalDuration.value
    }));
    durationConfig.value.durationDetailList = durationDetailList.map(v => ({
      ...v,
      durationId: undefined,
      durationDetailId: undefined,
      durationVal: Number(v.durationVal)
    }));
    Message.success("复制成功");
  } catch (error) {}
};
onMounted(() => {
  getPortraitListData();
});
</script>

<style lang="scss" scoped>
$border: 1px solid #dcdfe6;

.tabs {
  height: 60px;
  position: relative;
  border-bottom: $border;

  ::v-deep(.arco-btn) {
    position: absolute;
    right: 0;
    top: 20px;
  }

  ::v-deep(.arco-tabs-nav-tab),
  ::v-deep(.arco-tabs-nav-type-line .arco-tabs-tab) {
    height: 60px;
    line-height: 70px;
  }

  ::v-deep(.arco-tabs-nav-button-left) {
    margin-top: 10px;
  }

  ::v-deep(.arco-tabs-nav-button-right) {
    margin-top: 10px;
  }

  ::v-deep(.arco-tabs-nav::before) {
    background-color: unset;
  }
}

::v-deep(.arco-dropdown-option-content) {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;

  .arco-icon {
    display: none;
  }

  &:hover {
    color: #007dff;

    .arco-icon {
      display: inline;
    }
  }
}

.app-container {
  padding-bottom: 80px;
}

.tip {
  margin: 20px 0 13px;
  &__title {
    font-size: 14px;
    color: #4e5969;
    line-height: 22px;
    font-weight: bold;
  }
  &__desc {
    color: #86909c;
    font-size: 12px;
  }
}

.config {
  background: #f5f7fa;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  height: 40px;
  border-radius: 4px;
  line-height: 40px;

  span {
    color: #86909c;
    font-size: 12px;
  }
}

.four-column-table {
  .table-head,
  .row {
    grid-template-columns: repeat(4, 1fr);
  }
}

.five-column-table {
  .table-head,
  .row {
    grid-template-columns: repeat(4, 2fr) 1fr;
  }
}

.table {
  border: $border;

  .table-head {
    background: #f2f6fc;
    height: 44px;
    border-bottom: $border;

    span {
      font-size: 12px;
    }
  }

  .table-head,
  .row {
    display: grid;

    > div {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 20px;
    }
  }

  .table-body {
    .row {
      min-height: 50px;
      border-bottom: $border;

      > div {
        border-right: $border;
        padding: 10px 20px;

        ::v-deep(.arco-form-item) {
          margin-bottom: unset;
          padding: none;
        }

        ::v-deep(.arco-form-item-error) {
          .number-range {
            border: 1px solid red;
          }
        }
      }

      > div:last-child {
        border: none;
      }

      .outweigh {
        font-size: 20px;
        margin-right: 10px;
      }

      .number-range {
        border: $border;
        display: flex;
        align-items: center;
        height: 30px;
        gap: 10px;
        padding: 0 10px;
        border-radius: 4px;

        input {
          border: none;
          width: 50%;
          outline: none;
          text-align: center;

          &::-webkit-outer-spin-button,
          &::-webkit-inner-spin-button {
            -webkit-appearance: none;
          }

          &::placeholder {
            color: #c5c5c5;
          }

          *[type="number"] {
            -moz-appearance: textfield;
          }

          &:disabled {
            background: white;
            cursor: not-allowed;
          }
        }

        &:focus-within {
          border: 1px solid #007dff;
        }
      }
    }
  }

  .table-foot {
    height: 44px;
    display: flex;
    align-items: center;
  }
}

.save {
  position: absolute;
  background: white;
  bottom: 0;
  height: 64px;
  width: 100%;
  box-shadow: 0px -5px 10px 0px rgba(66, 78, 102, 0.08);
  border-radius: 0px 0px 10px 10px;
  display: flex;
  align-items: center;
  justify-content: end;
  padding-right: 20px;
  box-sizing: border-box;
}
</style>
